/*
 * MemoryMaps.cpp
 *
 *  Created on: May 26, 2011
 *      Author: stud
 */

#include "MemoryMaps.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "Map.h"

MemoryMaps::MemoryMaps(int mapNumber)
{
	mapNum = mapNumber;

	int i=0;
	for(i = 0; i< mapNum;i++)
	{
		sem[i] = new CountingSemaphore(1);
		maps[i] = new Map(20);

	}

	flagSem = new CountingSemaphore(1);

	writeMapFlag = 0;

	cout << "Maps created";

}

void MemoryMaps::writeFlagDown()
{
	writeMapFlag = 0;
	flagSem->signal();
}

void MemoryMaps::writeFlagUp()
{
	flagSem->wait();
	writeMapFlag = 1;
}

int MemoryMaps::getWriteMapFlag()
{
	return writeMapFlag;
}

sWord * MemoryMaps::getMapContents(int mapNumber,sWord * buffer)
{
	sem[mapNumber]->wait();
	copyBuffer(buffer, maps[mapNumber]->getData(),20);
	sem[mapNumber]->signal();

	return buffer;
}

sWord * MemoryMaps::copyBuffer(sWord *dest, sWord *source, int positions)
{
	int i=0;

	for(i=0;i<positions;i++)
	{
		dest[i].Word = source[i].Word;
	}

	return dest;
}

void MemoryMaps::setMapContents(int mapNumber, sWord * buffer)
{
	sem[mapNumber]->wait();
	copyBuffer(maps[mapNumber]->getData(),buffer,20);
	sem[mapNumber]->signal();
}

MemoryMaps::~MemoryMaps()
{

}

void MemoryMaps::initializeMaps(int mode)
{
	int i=0;

	for(i=0;i<mapNum;i++)
	{
		sem[i]->wait();
		maps[i]->initMap(mode);
		sem[i]->signal();
	}
}

void MemoryMaps::printMemoryMaps()
{
	int i =0;
	for(i = 0; i< mapNum;i++)
	{
		sem[i]->wait();
		cout << "\n" << "----- Memory map #"<< i <<"---------";
		maps[i]->showData();
		sem[i]->signal();
	}
}
